<template>
	<view class="search_content">
		<view class="address_tab">
			<text @tap="selTab(0)" :class="{ tab_active: tabIndex == 0 }">Stu Info</text>
			<text @tap="selTab(1)" :class="{ tab_active: tabIndex == 1 }">Authorise Loc</text>
			<text @tap="selTab(2)" :class="{ tab_active: tabIndex == 2 }">Check Loc</text>
		</view>
		<view class="search_box">
			<view class="search_list" v-if="tabIndex == 0">
				<view class="search_item" v-for="(item, index) in children" :key="index">
					<view class="item_text">
						<view>Name：{{ !!item.userName ? item.userName : '' }}</view>
						<view class="position_btn">
							<view @tap="initiateTargeting(item, 1, index)">Send Loc</view>
							<view @tap="initiateTargeting(item, 0, index)">Cancel Loc</view>
						</view>
					</view>
					<view style="color: #333; font-size: 16px;">Australian Mobile：{{ !!item.stuPhoneAbord ? item.stuPhoneAbord : '' }}</view>
				</view>
			</view>
			<view class="warrant_list" v-if="tabIndex == 1">
				<view class="nothing" v-if="warrantList.length == 0"><image src="../../static/img/nothing.png"></image></view>
				<view class="warrant_item" v-else v-for="(item, index) in warrantList" :key="index">
					<view class="item_text">
						<view>Name：{{ !!item.userName ? item.userName : '' }}</view>
						<!-- <view style="color: #FF8F58;">Agree</view> -->
					</view>
					<view class="warrant_btn">
						<view @tap="editPositionGet('1', index)">Agree</view>
						<view @tap="editPositionGet('2', index)">Refuse</view>
					</view>
				</view>
			</view>
			<view class="location_list" v-if="tabIndex == 2">
				<view class="nothing" v-if="locationList.length == 0"><image src="../../static/img/nothing.png"></image></view>
				<view class="location_item" v-else v-for="(item, index) in locationList" :key="index">
					<view class="item_text" @tap="getPosition(item.userId)">
						<view>Name：{{ !!item.userName ? item.userName : '' }}</view>

						<view>Date：{{ item.updateTime }}</view>
						
						<view class="position_btn" v-if="item.positionGetStatus != 0">
							<view @tap="removeAllPositionOrNot()">Del Record</view>
						</view>
						<view class="position_btn" v-else>
							<!-- nothing -->
						</view>
					</view>
					<view class="location_status">
						<view>Location：{{ item.positionGetStatus == 0 ? 'Requesting' : item.positionGetStatus == 1 ? 'Agreed' : 'Rfused' }}</view>
					</view>
					<view
						class="location_position"
						v-if="item.gruSysPosition != null"
						@tap="startMap(item.gruSysPosition.latitude, item.gruSysPosition.longitude, item.gruSysPosition.position)"
					>
						<view>Location：</view>
						<view>{{ item.gruSysPosition.position }}</view>
					</view>
					<view class="location_position" v-else>
						<view>Location：</view>
						<view>No Data</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import api from '../../api/otherApi.js';
import utils from '../../api/utils.js';
export default {
	data() {
		return {
			iconType: 'success',
			account: '',
			tabIndex: 0,
			userType: '',
			children: [],
			warrantList: [],
			locationList: [],
			authorizationArr: [],
			token: ''
		};
	},
	mounted() {
		// methods里面定义的方法, 需要赋值给window
		Vue.prototype.$changePage = this.changePage;
		//iOS调用方法

		// PDRCoreApp *pdrCoreApp = (PDRCoreApp *)[[[PDRCore Instance] appManager] activeApp];
		// PDRCoreAppFrame* pMainFrame = [pdrCoreApp valueForKey:@"_weexWebview"];
		// if (pMainFrame)
		// {
		//     NSString *jsStr = [NSString stringWithFormat:@"Vue.prototype.$changePage('%@','%@')", _latitude, _longitude];
		//
		//     [pMainFrame stringByEvaluatingJavaScriptFromString:jsStr];
		// }
	},
	methods: {
		
		changePage(x, y) {
			console.warn(x + '--' + y);
			uni.navigateBack();
		},
		removeAllPosition(){
			let _this = this;
			api.delBatchPositionGet(JSON.stringify(_this.locationList), _this.token);
			_this.locationList = [];
		},
		removeAllPositionOrNot(){
			let _this = this;
			uni.showModal({
			    title: 'Tips',
			    content: 'Delete?',
			    success: function (res) {
			        if (res.confirm) {
						setInterval(async () => {_this.removeAllPosition();}, 200);
			        } else if (res.cancel) {
			            console.warn()('取消');
			        }
			    }
			});
		},
		async getPosition(id) {
			// let data = await api.addPositionGet(`position/addPositionGet?stuId=${id}`);
			// console.log(data);
		},
		// 获取授权信息
		async getPositionGetByAuth(token) {
			let _this = this;
			let data = await api.getPositionGetByAuth(token);
			_this.authorizationArr = [...data.body];
			if (data.head.status) {
				if (!!data.body.length) {
					_this.warrantList = data.body;
				} else {
					_this.warrantList = [];
					uni.showToast({
						title: 'No Data！',
						icon: 'none',
						duration: 2000
					});
				}
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
		},
		// 查看位置
		getPositionGetByOri(token) {
			return api.getPositionGetByOri(token);
		},

		// 发起/取消定位
		async initiateTargeting(item, type, index) {
			let _this = this;
			uni.showLoading({
				title: 'Please wait...',
				mask: true
			});
			if (type == 1) {
				let data = await api.addPositionGet(`position/addPositionGet?stuId=${item.userId}`, _this.token);
				if (data.head.status) {
					uni.showToast({
						title: 'Success！',
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.showToast({
						title: data.head.msg,
						icon: 'none',
						duration: 2000
					});
				}
			} else {
				let data = await _this.getPositionGetByOri(_this.token);
				let obj = {};
				if (data.head.status) {
					if (!!data.body.length) {
						data.body.forEach(items => {
							if (items.targetId == item.userId) {
								obj = { ...items };
							}
						});
					} else {
						uni.showToast({
							title: 'No Data！',
							icon: 'none',
							duration: 2000
						});
					}
				} else {
					uni.showToast({
						title: data.head.msg,
						icon: 'none',
						duration: 2000
					});
				}
				obj.cancelType = '0';
				let cancelData = await api.delPositionGet(obj, _this.token);
				if (cancelData.head.status) {
					uni.showToast({
						title: 'Success！',
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.showToast({
						title: cancelData.head.msg,
						icon: 'none',
						duration: 2000
					});
				}
			}
			uni.hideLoading();
		},

		// 授权/拒绝
		async editPositionGet(status, index) {
			let _this = this;
			_this.authorizationArr[index].positionGetStatus = status;
			let data = await api.editPositionGet(_this.authorizationArr[index], _this.token);
			console.log(data);
			if (data.head.status) {
				uni.showToast({
					title: status == '1' ? 'Success' : 'Fail',
					icon: 'none',
					duration: 1000
				});
				setTimeout(async () => {
					if (status == '1') {
						_this.getPositionGetByAuth(_this.token);
					}
				}, 1500);
			}
		},

		// 选项卡
		async selTab(index) {
			let _this = this;
			_this.tabIndex = index;
			uni.showLoading({
				title: 'Please wait...',
				mask: true
			});
			if (index == 1) {
				_this.getPositionGetByAuth(_this.token);
			} else if (index == 2) {
				let data = await _this.getPositionGetByOri(_this.token);
				uni.hideLoading();
				if (data.head.status) {
					if (!!data.body.length) {
						// let delData = await api.delBatchPositionGet(JSON.stringify(data.body), _this.token);
						// console.log(delData);
						// if (delData.head.status) {
						// 	_this.locationList = delData.body;
						// } else {
						// 	console.log(delData.head.msg);
						// }
						
						console.log(data.body);
						_this.locationList = data.body;
						if (data.body[0].positionGetStatus == '1' && data.body[0].gruSysPosition != null) {
							_this.startMap(data.body[0].gruSysPosition.latitude, data.body[0].gruSysPosition.longitude, data.body[0].gruSysPosition.position)
						}
					} else {
						uni.showToast({
							title: 'No Data！',
							icon: 'none',
							duration: 2000
						});
					}
				} else {
					uni.showToast({
						title: data.head.msg,
						icon: 'none',
						duration: 2000
					});
				}
			} else {
				if (_this.userType == '家长') {
					let data = await api.parentGetStudent('user/parentGetStudent', _this.token);
					if (data.head.status) {
						if (!!data.body.length) {
							_this.children = data.body;
						}
					} else {
						uni.showToast({
							title: data.head.msg,
							icon: 'none',
							duration: 2000
						});
					}
				} else if (_this.userType == '监护人') {
					uni.getStorage({
						key: 'userInfo',
						async success(res) {
							let data = await api.getStuList(
								'user/getStuList',
								{
									stuGurdianId: res.data.userId,
									current: 1,
									size: 50
								},
								_this.token
							);
							if (data.head.status) {
								_this.children = data.body;
							} else {
								uni.showToast({
									title: data.head.msg,
									icon: 'none',
									duration: 2000
								});
							}
						}
					});
				}
			}
			uni.hideLoading();
		}, // 查看位置
		startMap(lat, lon, pos) {
			console.log("====================>>>>>>>>>>>>>>>>>>>>>>>>");
			if (plus.os.name == 'iOS') {
				
				// TestMapViewController为应用内创建的原生的ViewController类名,所调用页面的内容需要在原生代码中完成

				var UserDefaultsClass = plus.ios.importClass('NSUserDefaults');
				var standardUserDefaults = UserDefaultsClass.standardUserDefaults();
				plus.ios.invoke(standardUserDefaults, 'setObject:forKey:', lat, 'latitude');
				plus.ios.invoke(standardUserDefaults, 'setObject:forKey:', lon, 'longitude');
				plus.ios.invoke(standardUserDefaults, 'setObject:forKey:', pos, 'position');
				plus.ios.invoke(standardUserDefaults, 'synchronize');
				
				var notiClass = plus.ios.importClass("NSNotificationCenter");
				notiClass.defaultCenter().postNotificationNameobject("TestMap","NULL");

				// var newVCobj = plus.ios.newObject('TestMapViewController');
				// var UIApplicationClass = plus.ios.importClass('UIApplication');
				// var UIAppObj = UIApplicationClass.sharedApplication();
				// var del = plus.ios.invoke(UIAppObj, 'delegate');
				// // 如果当前应用delegate对象包含UIWindow对象并且变量名命名为“window”可以这么写，
				// // 否则需要根据实际代码情况修改
				// // 应用的delegate对象也可以添加一个返回UIViewController的方法
				// var appWindowObj = plus.ios.invoke(del, 'window');
				// var appRootController = plus.ios.invoke(appWindowObj, 'rootViewController');
				
				// setInterval(async () => {
				// 	plus.ios.invoke(appRootController, 'presentViewController:animated:completion:', newVCobj, 'YES', null);
				// 	}, 200);
			}
			if (plus.os.name == 'Android') {
				var mContext = plus.android.runtimeMainActivity();
				var Intent = plus.android.importClass('android.content.Intent');
				var intent = new Intent();
				intent.setClassName(mContext, 'app.TestMap');
				intent.putExtra('longitude', lon);
				intent.putExtra('latitude', lat);
				mContext.onActivityResult = function(requestCode, resultCode, data) {};
				// setInterval(async () => {
					mContext.startActivityForResult(intent, 1);
					// }, 200);
			}
			
			// let _this = this;
			// _this.removeAllPosition();
		}
	},
	async onShow() {
		let _this = this;
		let userId = ''
		uni.getStorage({
			key: 'userInfo',
			success(res) {
				_this.userType = res.data.userType;
				userId = res.data.userId
			}
		});
		uni.getStorage({
			key: 'token',
			success(res) {
				_this.token = res.data;
			}
		});

		if (_this.userType == '家长') {
			let data = await api.parentGetStudent('user/parentGetStudent', _this.token);
			if (data.head.status) {
				if (!!data.body.length) {
					_this.children = data.body;
				}
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
		} else {
			// _this.getPositionGetByAuth(_this.token);
			// _this.tabIndex = 1;
			let data = await api.getStuList(
				'user/getStuList',
				{
					stuGurdianId: userId,
					current: 1,
					size: 50
				},
				_this.token
			);
			if (data.head.status) {
				_this.children = data.body;
			} else {
				uni.showToast({
					title: data.head.msg,
					icon: 'none',
					duration: 2000
				});
			}
		}
	}
};
</script>

<style scoped>
.search_content {
	width: 100%;
	background-color: #f1f1f1;
	box-sizing: border-box;
	padding-bottom: 10px;
}

.address_tab {
	display: flex;
	justify-content: space-between;
	font-size: 16px;
	box-sizing: border-box;
}

.address_tab text {
	flex: 1;
	text-align: center;
	padding: 10px;
	box-sizing: border-box;
}

.search_bar {
	width: 100%;
	padding: 15px;
	box-sizing: border-box;
	background-color: #fff;
}

.input-row {
	width: 100%;
	border: solid 1px #ccc;
	height: 35px;
	display: flex;
	justify-content: flex-start;
	align-items: center;
	border-radius: 10px;
	padding: 0 5px;
	box-sizing: border-box;
}

.search_list,
.warrant_list,
.location_list {
	box-sizing: border-box;
	background-color: #fff;
}

.search_item,
.warrant_item,
.location_item {
	border-bottom: solid 1px #e5e5e5;
	padding: 20px 15px;
	box-sizing: border-box;
}

.search_item:last-child,
.warrant_item:last-child,
.location_item:last-child {
	border-bottom: none;
}

/* .search_item:first-child {
		padding-top: 0;
	} */

.search_item:last-child {
	/* padding-bottom: 0; */
	border: none;
}

.search_item > image {
	width: 75px;
	height: 75px;
	margin-right: 15px;
}

.search_item .position_btn {
	display: flex;
	justify-content: space-between;
}

.search_item .position_btn > view {
	font-size: 14px;
	width: 80px;
	height: 30px;
	line-height: 30px;
	text-align: center;
	border: solid 1px #f1f1f1;
	color: #fff;
	border-radius: 5px;
	background-color: #0599d7;
	margin-left: 10px;
}

.search_item .position_btn > view:last-child {
	background-color: #ff485d;
}

.search_item > .item_text {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.item_text > view {
	color: #666;
	font-size: 16px;
	margin-bottom: 5px;
}

.warrant_item > .item_text {
	display: flex;
	justify-content: space-between;
}

.warrant_item > .warrant_btn {
	display: flex;
	justify-content: center;
}

.warrant_btn > view {
	padding: 10px 25px;
	box-sizing: border-box;
	border: solid 1px #f1f1f1;
	font-size: 16px;
	margin: 20px 25px 0 25px;
	border-radius: 5px;
}

.warrant_btn > view:first-child {
	background-color: #0599d7;
	color: #fff;
}

.warrant_btn > view:last-child {
	background-color: #ff485d;
	color: #fff;
}

.location_item > .item_text {
	display: flex;
	justify-content: space-between;
}

.location_item > .location_position {
	margin-top: 5px;
}

.location_item > .location_position > view:first-child {
	font-size: 16px;
	color: #666;
}

.location_item > .location_position > view:last-child {
	font-size: 16px;
	color: #116;
}

.location_item .position_btn {
	display: flex;
	justify-content: space-between;
}

.location_item .position_btn > view {
	font-size: 14px;
	width: 80px;
	height: 30px;
	line-height: 30px;
	text-align: center;
	border: solid 1px #f1f1f1;
	color: #fff;
	border-radius: 5px;
	background-color: #0599d7;
	margin-left: 10px;
}

.location_item .position_btn > view:last-child {
	background-color: #ff485d;
}

.location_status > view {
	font-size: 16px;
	color: #333;
}

.tab_active {
	color: #0599d7;
	border-bottom: solid 2px #0599d7;
}

.nothing {
	position: fixed;
	width: 100%;
	height: 100%;
	text-align: center;
}

.nothing image {
	width: 150px;
	height: 150px;
	margin-top: 50%;
}
</style>
